<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
  name: "image-item",
});
</script>
<script setup lang="ts">
import { reactive, ref, withDefaults, toRefs } from "vue";
import { Router } from "@/utils/router";
type dataType = {
  src: string;
  width: string;
  height: string;
  border: string;
  borderDadius: string;
};
const props = withDefaults(defineProps<dataType>(), {
  src: "",
  width: "",
  height: "",
  border: "",
  borderDadius: "",
});
const height2 = ref("");
const width2 = ref("");
const emit = defineEmits(["click"]);
const imageClick = () => {
  emit("click");
};
const mode = ref("scaleToFill");
const imageShow = ref(false);
const imageLoad = () => {
  uni.getImageInfo({
    src: props.src, // 图片的路径，可以是网络图片或本地文件路径
    success: function (imageInfo) {
      imageShow.value = true;
      const widthNum = parseInt(props.width.split("rpx")[0]);
      const heightNum = parseInt(props.height.split("rpx")[0]);
      const largeKey = widthNum > heightNum ? "width" : "height";
      if (largeKey == "width") {
        const rate1 = widthNum / heightNum;
        const rate2 = imageInfo.width / imageInfo.height;
        if (rate1 > rate2) {
          mode.value = "widthFix";
          height2.value = "auto";
          width2.value = props.width;
        } else {
          mode.value = "heightFix";
          height2.value = props.height;
          width2.value = "auto";
        }
      } else {
        const rate1 = heightNum / widthNum;
        const rate2 = imageInfo.height / imageInfo.width;
        if (rate1 > rate2) {
          mode.value = "heightFix";
          height2.value = props.height;
          width2.value = "auto";
        } else {
          mode.value = "widthFix";
          height2.value = "auto";
          width2.value = props.width;
        }
      }
    },
    fail: function (error) {
      console.error("获取图片信息失败：", error);
    },
  });
};
</script>

<template>
  <view class="imageWrap" @click="imageClick">
    <image v-show="imageShow" :src="src" :mode="mode" @load="imageLoad" />
  </view>
</template>

<style lang="scss">
.imageWrap {
  width: v-bind(width);
  height: v-bind(height);
  border: v-bind(border);
  border-radius: v-bind(borderDadius);
  overflow: hidden;

  display: flex;
  justify-content: center;
  align-items: center;
  image {
    flex-shrink: 0;
    flex-grow: 0;
    width: v-bind(width2);
    height: v-bind(height2);
  }
}
</style>
